//==================客户端======================
const dateKit = require( "./util/dateKit");
const dataKit = require( "./util/dataKit");
const util = require( "./util/util")
const clientService = require( "./util/clientService")

/**
 * 登录
 * userNick 用户昵称
 */
exports.login = async (context) => {
    const {userNick} = context.data;
    const {openId,appOwnerOpenId} = context;

    if(!userNick){
        return {code:-1,msg:"userNick是必须的"};
    }
    
    let userInfo = await clientService.getUserByOpenId(context,openId);
    if(!userInfo){
        userInfo = {openId:openId,
                    createTime:dateKit.getCurrentDateTime(),
                    //抽奖次数默认0次
                    drawNum:0,
                    version:0,
                  };
    }
    
    userInfo.appOwnerOpenId=appOwnerOpenId;
    userInfo.userNick=userNick;
    userInfo.loginTime = dateKit.getCurrentDateTime();
    const result = await dataKit.insertOrUpdate(context,"user_info",userInfo);
    
    return {code:0,msg:"登录成功",data:result};
};

/**
 * 获取当前用户信息
 */
exports.getUserInfo = async (context) => {
  const {openId} = context;
  let userInfo = await clientService.getUserByOpenId(context,openId);
  return {code:0,msg:"获取成功",data:userInfo};
}

/**
 * 获取完成上传作品人数
 */
exports.getUploadWorkPeopleNum = async (context) => {
  let sys_setting = await dataKit.findOne(context,"sys_setting",{key:"sys_setting"});
  return {code:0,msg:"获取成功",data:sys_setting.uploadWorkPeopleNum};
}


/**
 * 获取弹幕列表
 */
exports.getBarrageList = async (context) => {
  let barrageList = await dataKit.find(context,"barrage",{},{limit:10,sort:{createTime:-1}});
  let list = [];
  for(let item of barrageList){
    list.push(item.content);
  }
  return {code:0,msg:"获取成功",data:list};
}

/**
 * 口味列表
 * @param {*} context 
 */
exports.getFlavorList = async (context) => {
  let list = await dataKit.find(context,"flavor",{},{sort:{index:1}});
  return {code:0,msg:"获取成功",data:list};
}


/**
 * 宣言表
 * @param {*} context 
 */
exports.getDeclarationList = async (context) => {
  let list = await dataKit.find(context,"declaration",{},{sort:{index:1}});
  return {code:0,msg:"获取成功",data:list};
}

/**
 * 选择宣言
 * @param {*} context 
 */
exports.pickDeclaration = async (context) => {
  let {_id} = context.data;
  if(!_id){
    return {code:-1,msg:"缺失参数_id"};
  }

  const {openId} = context;
  let userInfo = await clientService.getUserByOpenId(context,openId);
  let {userNick} = userInfo; 

  if(userInfo.declarationId){
    return {code:-2,msg:"您已经选过文案了，请勿重复选择！"}; 
  }

  userInfo.declarationId = _id;
  userInfo.drawNum++;

  let ok = await dataKit.updateBy_idWithVersionLock(context,"user_info",userInfo);
  if(ok==0){
    return {code:-999,msg:"网络繁忙，请稍后再试！",data:"并发错误！"}; 
  }

  //增加日志
  await dataKit.insertOne(context,"game_num_log",{
    openId,userNick,type:"pickDeclaration",num:1,remark:"用户选择宣言",createTime:dateKit.getCurrentDateTime()
  });

  let declaration = await dataKit.findOne(context,"declaration",{_id});
  //增加票数
  declaration.voteNum++;
  await dataKit.updateBy_id(context,"declaration",declaration);

  //增加弹幕
  await dataKit.insertOne(context,"barrage",{
    openId,userNick,context:userNick+" pick "+declaration.name,createTime:dateKit.getCurrentDateTime()
  });

  return {code:0,msg:"选择成功"};
}

/**
 * 选择口味
 * @param {*} context 
 */
exports.pickFlavor = async (context) => {
  let {_id} = context.data;
  if(!_id){
    return {code:-1,msg:"缺失参数_id"};
  }

  const {openId} = context;
  let userInfo = await clientService.getUserByOpenId(context,openId);
  let {userNick} = userInfo;

  if(userInfo.flavorId){
    return {code:-2,msg:"您已经选过文案了，请勿重复选择！"}; 
  }

  userInfo.flavorId = _id;
  userInfo.drawNum++;
 let ok = await dataKit.updateBy_idWithVersionLock(context,"user_info",userInfo);
  if(ok==0){
    return {code:-999,msg:"网络繁忙，请稍后再试！",data:"并发错误！"}; 
  }
  

  //增加日志
  await dataKit.insertOne(context,"game_num_log",{
    openId,userNick,type:"pickFlavor",num:1,remark:"用户选择口味",createTime:dateKit.getCurrentDateTime()
  });

  let flavor = await dataKit.findOne(context,"flavor",{_id});
  //增加票数
  flavor.voteNum++;
  await dataKit.updateBy_id(context,"flavor",flavor);

  //增加弹幕
  await dataKit.insertOne(context,"barrage",{
    openId,userNick,context:userNick+" pick "+flavor.name,createTime:dateKit.getCurrentDateTime()
  });
  
 
  return {code:0,msg:"选择成功"};
}

/**
 * 分享好友
 * @param {*} context 
 */
exports.share = async (context) => {
  const {openId} = context;
  let userInfo = await clientService.getUserByOpenId(context,openId);
  let {userNick} = userInfo;
  let createTime = dateKit.getCurrentDateTime();

  let type = "share";
  //查询今日的分享次数
  let count = await dataKit.count(context,"game_num_log",{openId,type,createTime:dateKit.getTodayCondiction});
  if(count>=3){
    return {code:-1,msg:"今日分享已经超过三次，不增加抽奖机会"}
  }

  userInfo.drawNum++;
  let ok = await dataKit.updateBy_idWithVersionLock(context,"user_info",userInfo);
    
  if(ok==0){
    return {code:-999,msg:"网络繁忙，请稍后再试！",data:"并发错误！"}; 
  }

  //增加日志
  await dataKit.insertOne(context,"game_num_log",{
     openId,userNick,type,num:1,remark:"分享",createTime
  });

  return {code:0,msg:"分享成功，增加1次抽奖机会"};
}

/**
 * 邀请好友投票
 * @param {*} context 
 */
exports.createInviteLog = async (context) => {
  const {openId} = context;
  //作品id
  const {workId} = context.data;
  if(!workId){
    return {code:-1,msg:"缺少workId参数"};
  }

  let userInfo = await clientService.getUserByOpenId(context,openId);
  let {userNick} = userInfo;
  let createTime = dateKit.getCurrentDateTime();
  let inviteLog = await dataKit.insertOne(context,"invite_log",{openId,userNick,createTime,workId});
  return {code:0,msg:"操作成功",data:{inviteLogId:inviteLog._id}};
}

/**
 * 通过邀请码获取作品信息
 * @param {*} context 
 */
exports.getWorkByInviteLogId = async (context) => {
  let {inviteLogId} = context.data;
  if(!inviteLogId){
    return {code:-1,msg:"缺少参数inviteLogId"};
  }
  let inviteLog = await dataKit.findOne(context,"invite_log",{_id:inviteLogId});
  let {workId} = inviteLog;
  let work = await dataKit.findOne(context,"work",{_id:workId});
  return {code:0,msg:"获取成功",data:work};
}

/**
 * 通过作品id获取作品信息
 * @param {*} context 
 */
exports.getWorkByWorkId = async (context) => {  
  let {workId} = context.data;
  if(!inviteLogId){
    return {code:-1,msg:"缺少参数inviteLogId"};
  }
  let work = await dataKit.findOne(context,"work",{_id:workId});
  return {code:0,msg:"获取成功",data:work};
}

/**
 * 获取我的作品信息
 * @param {*} context 
 */
exports.getMyWork = async (context) => {
  let {openId} = context.data;
  let workList = await dataKit.find(context,"work",{openId:openId},{sort:{createTime:-1,limit:1}});
  if(!workList || workList.length==0){
    return {code:-1,msg:"您尚未上传作品"};
  }

  let work = workList[0];
  return {code:0,msg:"获取成功",data:work};
}


/**
 * 上传作品
 * @param {*} context 
 */
exports.uploadWork = async (context) => {  
  const {openId} = context;
  //作品图片url
  let {url,name,phone} = context.data;
  let check = util.checkParamsNull(context,"url,name,phone");
  if(check){
    return check;
  }
  
  let userInfo = await clientService.getUserByOpenId(context,openId);
  let {userNick} = userInfo;
  let createTime = dateKit.getCurrentDateTime();

  let approvingCount = await dataKit.count(context,"work",{openId,status:0});
  if(approvingCount>0){
    return {code:-1,msg:"上传失败，您的作品正在审核中，请勿重新上传"};
  }

  let successCount = await dataKit.count(context,"work",{openId,status:1});
  if(successCount>0){
    return {code:-2,msg:"上传失败，您的作品已通过，请勿重新上传"};
  }

  let work = {url,userNick,name,phone,openId,createTime,status:0};
  await dataKit.insertOne(context,"work",work);

  await clientService.addDrawNum(context,userInfo,3,"uploadWork","上传作品")

  return {code:0,msg:"上传成功，增加3次游戏机会",data:1};
}

/**
 * 投票
 * @param {*} context 
 */
exports.vote = async (context) => {
  //inviteLogId-邀请码(无则不传) type:1-口味 2-宣言 3-瓶身创作 
  const {openId} = context;
  const {inviteLogId,type,_id} = context.data;
  let check = util.checkParamsNull(context,"type,_id");
  if(check){
    return check;
  }

  let userInfo = await clientService.getUserByOpenId(context,openId);

   //todo 判断投票次数限制
  let checkVoteNum = await clientService.checkVoteNum(context,openId,type,inviteLogId,_id);
  if(checkVoteNum){
    return checkVoteNum;
  }

  if(type==1){
    await clientService.voteForFlavor(context,_id);
  }else if(type==2){
    await clientService.voteForDeclaration(context,_id);
  }else if(type==3){
    await clientService.voteForWork(context,_id);
  }
  
  //保存投票日志
  await clientService.addVoteLog(context,userInfo,_id,type,inviteLogId);

  //todo 用户加分
  await clientService.addDrawNum(context,userInfo,1,"vote","投票")

  return {code:0,msg:"投票成功"};
}


/**
 * 排行榜列表
 * @param {*} context 
 */
exports.getLeaderboardList = async (context) => {
  //type-类型：1-口味选择 2-宣言选择 3-瓶身作品
  const {type} = context.data;
  let check = util.checkParamsNull(context,"type");
  if(check){
    return {code:-1,msg:"缺少status参数"};
  }

  let list = [];
  if(type==1){
    list = await clientService.getFlavorList(context);
  }else if(type==2){
    list = await clientService.getDeclarationList(context);
  }else if(type==3){
    list = await clientService.getWorkList(context);
  }


  return {code:0,msg:"获取成功",data:list};
}


// /**
//  * 获取商品列表
//  */
// exports.getProductList = async (context) => {
//     let result = await clientService.getProductList(context);
//     return {code:0,msg:"获取成功",data:result};
// };

// /**
//  * 会员身份识别
//  */
// exports.isTaobaoMember = async (context) => {
//     let result = await clientService.isTaobaoMember(context,context.mixNick);
//     return {code:0,msg:"获取成功",data:result};
// };

// /**
//  * 发送权益
//  */
// exports.sendBenefit = async (context) => {
//     const {openId,ename} = context.data; 
//     const result = await clientService.sendBenefit(context,openId,ename,util.uuid());
//     return {code:0,msg:"发奖成功",data:result};
// }

